<script setup>
import { ref, onMounted, watch } from 'vue';
import { useRoleStore } from '@/stores/roleStore.js';
import RoleEdit from '@/views/user/RoleEdit.vue';
import RoleDetail from '@/views/user/RoleDetail.vue';
import RoleAdd from '@/views/user/RoleAdd.vue';
const roleStore = useRoleStore();
const tableData = ref([]);
const roleEditRef = ref(null);
const roleAddRef = ref(null); // 新增引用
const roleDetailRef = ref(null);
const currentPage = ref(1); // 正确创建本地响应式变量


onMounted(() => {
  roleStore.getRoleList();
});

watch(
    () => roleStore.roleList,
    (newVal) => {
      tableData.value = newVal;
    },
    { deep: true }
);

// 新增处理函数
const handleAdd = () => {
  roleAddRef.value.show();
};


const handleEdit = (roleInfo) => {
  console.log("编辑的角色信息:", roleInfo); // 检查 roleInfo 是否包含 id
  roleEditRef.value.show(roleInfo);
};

//查看详情
const handleDetail = (roleInfo) => {
  console.log("查看的角色信息:", roleInfo);
  roleDetailRef.value.show(roleInfo);
}

const handleDelete = (id) => {
  roleStore.deleteRole(id);
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  roleStore.pageInfo.pageNum = val;
  roleStore.getRoleList();
};
</script>

<template>
  <div>
    <div style="margin-bottom: 15px;">
      <el-button type="primary" @click="handleAdd">新增角色</el-button>
    </div>
    <el-table :data="tableData" border>
      <el-table-column label="角色名称" prop="name"></el-table-column>
      <el-table-column label="角色编码" prop="code"></el-table-column>
      <el-table-column label="数据权限范围" prop="dataScope"></el-table-column>
      <el-table-column label="操作">
        <template v-slot="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row.id)">删除</el-button>
          <el-button type="primary" size="small" @click="handleDetail(scope.row)">查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        :total="roleStore.pageInfo.total"
        :page-size="roleStore.pageInfo.pageSize"
        v-model:current-page="currentPage"
        @current-change="handleCurrentChange"
        layout="prev, pager, next, jumper, ->, total"
        background
    />

    <RoleEdit ref="roleEditRef"/>
    <RoleDetail ref="roleDetailRef"/>
    <RoleAdd ref="roleAddRef"/> <!-- 新增组件引用 -->
  </div>
</template>

<style scoped>
.el-pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>
